<?php

namespace app\roomcall\controller;

use app\common\model\Orderproject;
use app\common\model\ProjectCategory;
use app\common\model\UserProject as UserProjectM;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use app\common\service\VoiceService;
use think\Db;
use think\Exception;


class Project extends Home
{
    public $noNeedLogin = [];

    /**
     * 获取项目分类
     */
    public function cateLists()
    {
        if ($this->request->isPost()) {
            $categoryM = new ProjectCategory();
            $result = $categoryM->getProjectCate($this->store_id);
            $this->result('查询成功', $result, 200);
        }
        $this->result('无效的请求方式', '', 204);
    }

    /**
     * 获取项目列表
     */
    public function projectLists()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['cate_id']))  $this->result('项目分类不能为空', '', 204);
            $limit = !empty($post['limit']) ? $post['limit'] : 10;
            $categoryM = new \app\common\model\Project();
            $result = $categoryM->getProjectList($this->userInfo['store_id'], $post['cate_id'], '0', '0', '0', '', $limit, '0');
            $this->result('', $result, 200);
        }
        $this->result('无效的请求方式', '', 204);
    }

    /**
     * 获取主项
     */
    public function getMainProject()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_user_project')->alias('up')
                ->field('p.id,p.name')
                ->leftJoin('qt_project p', 'p.id=up.project_id')
                ->where([
                    'p.store_id' => $this->userInfo['store_id'],
                    'p.status' => '1',
                    'p.type' => '1',
                    'up.engineer_id' => $this->userInfo['id'],
                ])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 获取副项
     */
    public function getOtherProject()
    {
        if ($this->request->isPost()) {

            $data = Db::name('qt_user_project')->alias('up')
                ->field('p.id,p.name')
                ->leftJoin('qt_project p', 'p.id=up.project_id')
                ->where([
                    'p.store_id' => $this->userInfo['store_id'],
                    'p.status' => '1',
                    'p.type' => '2',
                    'up.engineer_id' => $this->userInfo['id'],
                ])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }

    /**
     * 更换项目
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function changeProject()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            //老项目订单
            $order_project = Db::name('qt_order_project')
                ->where('id', $post['order_project_id'])
                ->where('is_delete',2)
                ->find();
            if (empty($order_project)) {
                $this->result('没有查询到项目', '', 204);
            }
            if ($order_project['project_id'] == $post['new_project_id']) {
                $this->result('所换项目与原来一致，请重新选择', '', 204);
            }

            if (empty($post['engineer_id'])) {
                $this->result('技师ID不能为空', '', 204);
            }
            //新项目
            $new_project = Db::name('qt_project')->where('id', $post['new_project_id'])->find();
            $old_project = Db::name('qt_project')->where('id', $order_project['project_id'])->find();
            if (!empty($order_project['start_time'])) {
                $start_time = $order_project['start_time'];
                if ($new_project['time'] > $old_project['time']) {
                    $ceil = $new_project['time'] - $old_project['time'];
                    $end_time = $order_project['end_time'] + ($ceil * 60);
                } else {
                    $ceil = $old_project['time'] - $new_project['time'];
                    $end_time = $order_project['end_time'] - ($ceil * 60);
                }
            } else {
                $start_time = null;
                $end_time = null;
            }
            //新订单信息
            $new_order_project_insert = [
                'store_id' => $order_project['store_id'],
                'name' => $new_project['name'],
                'old_name' => $old_project['name'],
                'created_order_id' => $order_project['created_order_id'],
                'order_id' => $order_project['order_id'],
                'engineer_id' => $post['engineer_id'],
                'project_id' => $post['new_project_id'],
                'room_id' => $order_project['room_id'],
                'hand_card_id' => $order_project['hand_card_id'],
                'order_type' => '1',
                'num' => $order_project['num'],
                'price' => $new_project['price'],
                'status' => $order_project['status'],
                'is_add' => '1',
                'is_change' => '1',
                'created_time' => time(),
                'sale_id' => $this->userInfo['id'],
                'start_time' => $start_time,
                'end_time' => $end_time,
            ];
            //插入新项目
            $new_project_id = Db::name('qt_order_project')->insertGetId($new_order_project_insert);
            //更新老项目数据
            Db::name('qt_order_project')
                ->where('is_delete',2)
                ->where(['id' => $post['order_project_id']])
                ->update(['status' => '5', 'is_change' => '3']);
            if ($start_time == null) {
                $work_status = '5';
                $queue_status = '2';
            } else {
                $work_status = '4';
                $queue_status = '3';
            }
            Db::name('qt_order_queue')
                ->where(['user_id' => $post['engineer_id']])
                ->update([
                    'old_name' => $order_project['name'],
                    'start_time' => $start_time,
                    'status' => $queue_status,
                    'end_time' => $end_time,
                    'room_id' => $order_project['room_id'],
                    'order_project_id' => $new_project_id
                ]);
            Db::name('qt_users')
                ->where(['id' => $order_project['engineer_id']])
                ->update(['work_status' => $work_status]);
            //判断接待提成规则
            //1=按下单人项目不管技师做什么项目，2=按技师上钟项目不管下单人下什么项目，3=下单人下单项目和技师上钟项目必须相同才有提成
            if ($this->store_info['receiver_order_commission_type'] == '2') {
                //删除之前的提成并插入新的接待提成和技师提成
                Db::startTrans();

                try {
                    //删除订单提成
                    Db::name('qt_commission_log')->where(['type' => '1', 'order_project_id' => $order_project['id']])->delete();
                    //插入新的提成
                    $project = Db::name('qt_project')->where('id', $post['new_project_id'])->find();
                    //普通提成
                    $commission = new OrdinaryService();
                    $commission = $commission->showCommission('1', '1', $project);
                    //计算接待提成
                    $receiver = new ReceiverService();
                    $receiver = $receiver->showCommission('1', '1', $project);
                    if ($this->store_info['floor_commission_type'] == '1') {
                        $cashier_id = $order_project['created_order_id'];
                    } else {
                        $cashier_id = $order_project['created_order_id'];
                    }
                    $insert = [
                        'store_id' => $this->store_id,
                        'cashier_id' => $cashier_id,//接待人
                        'user_id' => $post['engineer_id'],//技师
                        'room_id' => $order_project['room_id'],
                        'money' => $new_project['price'],
                        'commission' => $commission,//技师提成
                        'receiver' => $receiver,//接待提成
                        'product_id' => $order_project['project_id'],
                        'type' => '1',
                        'created_time' => time(),
                        'is_pay' => '1',
                        'order_project_id' => $new_project_id,
                        'status' => $order_project['order_type'],
                        'is_add' => $order_project['order_type'],
                    ];
                    Db::name('qt_commission_log')->insert($insert);
                    Db::commit();
                } catch (Exception $exception) {
                    Db::rollback();
                    $this->result('操作失败' . $exception->getFile() . $exception->getLine() . $exception->getMessage(), '', 204);
                }
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }

    }

    /**
     * 加钟
     */
    public function addClock()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['project_id']) || empty($post['num'])) {
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id' => $post['engineer_id']])
                ->find();
            $order_project = Db::name('qt_order_project')
                ->where('is_delete',2)->where('id', $find['order_project_id'])->find();
            $project = Db::name('qt_project')->where('id', $post['project_id'])->find();
            $add = Db::name('qt_users')->where('id', $post['engineer_id'])->value('is_add');
            //下新项目
            $insertOrderProject = [
                'store_id' => $order_project['store_id'],
                'name' => $project['name'],
                'created_order_id' => $this->userInfo['id'],
                'order_id' => $order_project['order_id'],
                'engineer_id' => $order_project['engineer_id'],
                'project_id' => $post['project_id'],
                'room_id' => $order_project['room_id'],
                'hand_card_id' => $order_project['hand_card_id'],
                'old_card_id' => $order_project['old_card_id'],
                'order_type' => '5',
                'num' => '1',
                'price' => $project['add_block_price'],
                'status' => 2,
                'is_add' => $add,
                'start_time' => time(),
                'end_time' => $order_project['end_time'] + ($project['add_block_time'] * 60),
                'is_change' => '1',
                'created_time' => time(),
            ];
            try {
                //更新项目订单状态
                Db::name('qt_order_project')->where('id', $order_project['id'])->update(['end_time' => $order_project['end_time'] + ($project['add_block_time'] * 60), 'status' => '2']);
                Db::name('qt_order_project')->insert($insertOrderProject);
                Db::name('qt_order_queue')->where('user_id', $order_project['engineer_id'])->update(['end_time' => $order_project['end_time'] + ($project['add_block_time'] * 60)]);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->result('加钟失败', '', 204);
            }
            $this->result('加钟成功', '', 200);
        }
    }

    /**
     * 技师上钟
     */
    public function startProject()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['order_id']) || empty($post['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($post['order_id'], $post['engineer_id'], '1');
            if ($res['status']) {
                //上钟成功播报
                $voiceResult = VoiceService::createVoice('上钟成功');
                if($voiceResult['code'] == 0){
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'],'上钟成功',$voiceResult['data'],'5','3',$post['engineer_id']);
                }
                $this->result('上钟成功', '', 200);
            } else {
                $this->result('上钟失败', $res['msg'], 204);
            }
        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     *下钟操作
     */
    public function endProject()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if (empty($post['order_id']) || empty($post['engineer_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($post['order_id'], $post['engineer_id'], '2');
            if ($res['status']) {
                //下钟成功播报
                $voiceResult = VoiceService::createVoice('下钟成功');
                if($voiceResult['code'] == 0){
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'],'下钟成功',$voiceResult['data'],'6','3',$post['engineer_id']);
                }
                $this->result('下钟成功', '', 200);
            } else {
                $this->result('下钟失败', $res['msg'], 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 添加项目
     */
    public function addProject()
    {

        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $post = $this->request->post();
            $validate = new \app\web\validate\Order();
            if (!$validate->scene('add')->check($post)) {
                $this->result($validate->getError(), '', 204);
            }
            if (empty($post['man_num'])) {
                $post['man_num'] = 0;
            } else {
                $sex = '1';
                $number = $post['man_num'];
            }
            if (empty($post['woman_num'])) {
                $post['woman_num'] = 0;
            } else {
                $sex = '2';
                $number = $post['woman_num'];
            }
            if (empty($post['other_num'])) {
                $post['other_num'] = 0;
            } else {
                $sex = '3';
                $number = $post['other_num'];
            }
            $totalNum = $post['man_num'] + $post['woman_num'] + $post['other_num'];
            if ($post['order_type'] == '1' && $totalNum <= 0) {
                $this->result('请至少选择一个技师', '', 204);
            }
            if (empty($post['hand_card_id'])) {
                $post['hand_card_id'] = '0';
            }
            //延迟时间为0
            if (empty($post['delay'])) {
                $post['delay'] = 0;
            }
            //默认立刻排钟
            if (empty($post['time_type'])) {
                $post['time_type'] = 1;
            }
            $post['create_id'] = $userInfo['id'];
            //不自动排钟
            if ($post['order_type'] == '1' && $this->store_info['is_auto_queue'] == '0') {
                $projectName = Db::name('qt_project')->where('id', $post['project_id'])->value('name');
                $roomOrder = [
                    'store_id' => $this->userInfo['store_id'],
                    'room_id' => $post['room_id'],
                    'project_id' => $post['project_id'],
                    'project_name' => $projectName,
                    'sex' => $sex,
                    'number' => $number,
                    'create_id' => $userInfo['id'],
                    'create_time' => time(),
                ];
                $save = Db::name('qt_wait')->insert($roomOrder);
                if ($save) {
                    $this->result('下单成功', '', 200);
                }
            }
            //延时排钟记录
            if ($post['time_type'] == '2') {
                if (empty($post['delay'])) {
                    $this->result('缺少延时排钟时间', '', 200);
                }
                $insertData = [
                    'store_id' => $this->userInfo['store_id'],
                    'project_id' => $post['project_id'],
                    'room_id' => $post['room_id'],
                    'man_num' => $post['man_num'],
                    'woman_num' => $post['woman_num'],
                    'other_num' => $post['other_num'],
                    'status' => 1,
                    'create_id' => $post['create_id'],
                    'delay_time' => $post['delay'],
                    'create_time' => time(),
                ];
                $insert = Db::name('qt_room_delay')->insert($insertData);
                if ($insert) {
                    $this->result('下单成功', '', 200);
                } else {
                    $this->result('延时排钟失败', '', 200);
                }
            }
            //判断当前房间内未结账的项目数
            $usedNumber = Db::name('qt_order_project')
                ->whereNotNull('engineer_id')
                ->where('is_delete',2)
                ->where(['pay_status' => '0', 'room_id' => $post['room_id'], 'real_end_time' => null])
                ->count();
            $roomNumber = Db::name('qt_room')->where(['id' => $post['room_id']])->value('bed_num');
            $totalNum = $post['man_num'] + $post['woman_num'] + $post['other_num'];
            if (($usedNumber + $totalNum) > $roomNumber) {
                $this->result('超出房间床位数', '', 204);
            }
            $orderModel = new \app\common\model\Order();
            $code = $orderModel->create_order($post, $userInfo);
            if ($code['code'] == '200') {
                $this->result('下单成功', '', 200);
            }
        } else {
            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 所属项目下的技师
     **/
    public function getEngineerList()
    {
        $project_id   = $this->request->post('project_id',0);
        $UserProjectM   = new UserProjectM();
        $list           = $UserProjectM->getEngineer($project_id);
        $this->result('获取成功',$list,200);
    }


    /**
     * 会做项目的空闲技师
     */
    public function engineerEmpty()
    {
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if (empty($getData['project_id'])) {
                $this->result('缺少参数', '', 204);
            }
            $where = [];
            if (!empty($getData['work_number'])) {
                $where = ['u.work_number'=>$getData['work_number']];
            }
            $data = Db::name('qt_user_project')
                ->field('p.id,u.work_number,u.work_status')
                ->alias('p')
                ->leftJoin('qt_users u', 'u.id = p.engineer_id')
                ->where('p.project_id', $getData['project_id'])
                ->where(['u.work_status' => '1','u.status'=>'0'])
                ->where($where)
                ->select();
            $this->result('查询成功', $data, 200);

        }
        $this->result('无效的请求', '', 204);
    }


}
